
import { ref, watch } from 'vue'
import { debounce } from 'lodash'
/**
 * 通用列表请求hook
 * 
 * props 是一个对象
 * api 属性  是接口请求方法
 */
export const useFetchList = (props) => {

  const filterParams = ref({})

  const paginationParams = ref({
    page: 1,
    size: 4,
    order: "createTime",
    sort: "desc"
  })

  const dataSource = ref([])

  const total = ref(0)

  const loading = ref(false)

  /**
   * 请求数据的方法
   */
  const getData = debounce(async () => {
    loading.value = true
    const data = await props.api({ ...paginationParams.value, ...filterParams.value })
    data.list.forEach(item => {
      item.key = item.id
    })

    dataSource.value = data.list
    total.value = data.pagination.total
    loading.value = false
  }, 300)

  /**
   * 每次变化重新请求接口
   */
  watch([paginationParams], () => {
    getData()
  }, {
    immediate: true,
    deep: true
  })

  return {
    dataSource,
    paginationParams,
    filterParams,
    getData,
    total,
    loading
  }

}